package DBConnection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private SessionFactory sessionFactory;
	private Session session;

	protected HibernateUtil() {
		try {
			// Create the SessionFactory from standard (hibernate.cfg.xml)
			// config file.
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
			session = sessionFactory.openSession();
		} catch (Throwable ex) {
			// Log the exception.
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	protected Session getCurrentSession() {
		return session;
	}

	protected void commitTransaction() {
		session.getTransaction().commit();
	}

	protected void beginTranSaction() {
		session.beginTransaction();
	}

	protected Transaction getTransaction() {
		if (sessionFactory.getCurrentSession().getTransaction() == null)
			sessionFactory.getCurrentSession().beginTransaction();
		return sessionFactory.getCurrentSession().getTransaction();
	}

	protected SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	protected void rollback() {
		sessionFactory.getCurrentSession().getTransaction().rollback();
	}
}
